package com.loong.tool.lang;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 流工具类
 *
 * @author 张成轩
 */
public class Streams {

	/** 读写单元大小 */
	private static final int SIZE = 1024;

	/**
	 * 写入文件
	 * 
	 * @param is 输入流
	 * @param dir 文件夹路径
	 * @param name 文件名称
	 * @throws IOException IO异常
	 */
	public static void write(InputStream is, String dir, String name) throws IOException {

		write(is, new File(dir, name));
	}

	/**
	 * 写入文件
	 * 
	 * @param is 输入流
	 * @param dir 文件夹
	 * @param name 文件名称
	 * @throws IOException IO异常
	 */
	public static void write(InputStream is, File dir, String name) throws IOException {

		write(is, new File(dir, name));
	}

	/**
	 * 写入文件
	 * 
	 * @param is 输入流
	 * @param file 文件
	 * @throws IOException IO异常
	 */
	public static void write(InputStream is, String file) throws IOException {

		write(is, new File(file));
	}

	/**
	 * 写入文件
	 * 
	 * @param is 输入流
	 * @param file 文件
	 * @throws IOException IO异常
	 */
	public static void write(InputStream is, File file) throws IOException {

		file.getParentFile().mkdirs();
		FileOutputStream fs = new FileOutputStream(file);
		byte[] buffer = new byte[SIZE];
		int count = 0;
		try {
			while ((count = is.read(buffer)) != -1)
				fs.write(buffer, 0, count);
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				fs.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 读取文件
	 * 
	 * @param os 输出流
	 * @param file 文件路径
	 * @throws IOException IO异常
	 */
	public static void read(OutputStream os, String file) throws IOException {

		read(os, new File(file));
	}

	/**
	 * 读取文件
	 * 
	 * @param os 输出流
	 * @param file 文件
	 * @throws IOException IO异常
	 */
	public static void read(OutputStream os, File file) throws IOException {

		FileInputStream is = new FileInputStream(file);
		byte[] buffer = new byte[SIZE];
		int count = 0;
		try {
			while ((count = is.read(buffer)) != -1)
				os.write(buffer, 0, count);
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}
	}
}
